let app = getApp()
const util = require('../../util/util.js')
Page({
    /**
   * 页面的初始数据
   */
  data: {
    del: []
  },
  onLoad(options) {
    let that = this
    let photo = [],
      imageStr = null,
      imageNum = 0,
      contentLength
    dd.getStorage({
      key: 'updateInspect' + options.id,
      success: function(res) {
        if (res.data.photo[0] != "") {
          imageNum = res.data.photo.length
          for (let i = 0; i < res.data.photo.length; i++) {
            photo[i] = res.data.photo[i]
          }
          if (imageNum == 3) {
            that.setData({
              hide: true
            })
          }
        }
        if (res.data.recordContent == null) {
          contentLength = 0
        } else {
          contentLength = res.data.recordContent.length
        }
        that.setData({
          id: res.data.id,
          categoryId: res.data.categoryId,
          inspectItemId: res.data.inspectItemId,
          item: res.data.item,
          status: res.data.status,
          content: res.data.content,
          photo: photo,
          imageNum: imageNum,
          recordContent: res.data.recordContent,
          contentLength: contentLength,
          className: res.data.className,
          address: res.data.address
        })
        dd.hideLoading()
      },
      fail: res => {
        dd.showToast({
          content: '网络异常！',
          type: 'fail'
        })
      }
    })
  },
  switchChange: function(e) {
    if (e.detail.value == false) {
      this.setData({
        status: 4,
        contentLength: 0,
        photo: [],
        hide: false,
        imageNum: 0,
      })
    } else {
      this.setData({
        status: 3,
        recordContent: null,
        contentLength: 0,
        photo: [],
        imageNum: 0
      })
    }
  },


  inputContent: function(e) {
    e.detail.value = app.trim(e.detail.value)
    this.setData({
      contentLength: parseInt(e.detail.value.length),
      recordContent: e.detail.value
    })
  },
  chooseImage: function(e) {
    var that = this;
    let photo = this.data.photo
    let imageNum = this.data.imageNum
    dd.chooseImage({
      count: 3,
      sourceType: ['camera', 'album'],
      success: res => {
        dd.showLoading({
          title: "图片上传中",
          mask: true
        })

        let tempImg = res.filePaths
        let imgUrl = []
        for (let i = 0; i < tempImg.length; i++) {
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload',
            filePath: res.filePaths[i],
            fileName: 'file',
            fileType:'image' ,
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {

              if (res.data == "fail") {
                dd.showToast({
                  content: "图片上传失败",
                  type: "fail"
                })
              } else {
                dd.showToast({
                  title: "上传成功",
                  type: "success"
                })

                photo.push(app.imageUrl + res.data)
                imgUrl.push(res.data)
                imageNum++
                this.setData({
                  photo: photo,
                  imageNum: this.data.photo.length
                })
                if (this.data.imageNum == 3) {
                  this.setData({
                    hide: true
                  })
                }
              }
            },
            fail: res => {
              dd.showToast({
                content: "图片上传失败",
                type: "fail"
              })
            }
          })
        }
        that.setData({
          imageStr: imgUrl.join(",")
        })


      }
    })
  },

  previewImageDeal: function(e) {
    let current = e.currentTarget.id
    dd.previewImage({
      current: current,
      urls: this.data.photo
    })
  },


  deleteImage: function(e) {
    let that = this,
      imgIndex = parseInt(e.currentTarget.id),
      photo = this.data.photo,
      target = photo[imgIndex],
      temp = [],
      del = this.data.del
    for (let i = 0; i < photo.length; i++) {
      if (i != imgIndex) {
        temp.push(photo[i])
      } else {
        del.push(photo[i])
      }
    }
    dd.showActionSheet({
      items: ['删除这张照片'],
      cancelButtonText: '取消',
      success: res => {
        if (!res.cancel) {
          that.setData({
            photo: temp,
            del: del,
            imageNum: that.data.imageNum - 1,
            hide: false
          })
        }
      }
    })
    that.setData({
      imageStr: temp.join(",")
    })
  },
  submit: function(e) {
    let that = this,
      item = this.data,
      commit

    if (item.status == 4) {
      if (item.recordContent == null || item.recordContent == undefined || item.recordContent == "") {
        commit = 0
      }
    }
    if (commit == 0) {
      dd.showToast({
        content: '请输入处理记录',
        type: "fail"
      })
    } else {
      dd.confirm({
        title: "温馨提示",
        content: "是否保存当前修改",
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        success:(result) =>{
          if (result.confirm) {
            that.commitForm()
          }
        }
      })
    }
  },
  commitForm: function() {
    let that = this
    let dataPhoto = this.data.photo
    let photo = ""
    for (let i = 0; i < this.data.photo.length; i++) {
      if (i == dataPhoto.length - 1) {
        photo = photo + dataPhoto[i].substring(dataPhoto[i].indexOf("/image/"))
      } else {
        photo = photo + dataPhoto[i].substring(dataPhoto[i].indexOf("/image/")) + ","
      }
    }

    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem2/updateInspectConditionById',
      method: 'POST',
      headers:{
        "Content-Type":"application/json"
      },
      data: JSON.stringify({
        id: this.data.id,
        photo: photo,
        recordContent: this.data.recordContent,
        status: this.data.status,
        updateUserId: app.globalData.userId
      }),
      dataType: 'json',
      success: res => {
        console.log(res)
        for (let i = 0; i < that.data.del.length; i++) {
          let del = that.data.del[i].split("image/")[1]
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteFile',
            method: 'POST',
            data: {
              filename: del
            },
            dataType: 'json',
            success: res => {

            }
          })
        }
        dd.showToast({
          content: '提交成功',
          type:"success" ,
        })
        //异常推送
        if (4 == that.data.status) {
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/safetyReport',
            method: 'POST',
            headers:{
              "Content-Type":"application/json"
            },
            data: JSON.stringify({
              schoolId: app.globalData.departmentId,
              safetyLevel: 5,
              categoryId: that.data.categoryId,
              address: that.data.address,
              content: that.data.recordContent,
              photo: that.data.imageStr,
              reporter: app.globalData.userId,
              inspectConditionId: that.data.id,
              itemContent: that.data.content
            }),
            dataType: 'json',
            success: res => {
              if (res.data.res == "success") {
                let safetySceneId = res.data.data
                dd.httpRequest({
                  url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
                  method: 'GET',
                  data: {
                    schoolId: app.globalData.departmentId
                  },
                  dataType: 'json',
                  success: res => {
                    let access_token = res.data.access_token
                    dd.httpRequest({
                      url: app.baseUrl + '/DingDingSystem/getChargeManDingDingId',
                      method: 'POST',
                      headers:{
                        "Content-Type":"application/json"
                      },
                      data: JSON.stringify({
                        categoryId: that.data.categoryId,
                        schoolId: app.globalData.departmentId
                      }),
                      dataType: 'json',
                      success: res => {
                        let unbind = []
                        for (let i = 0; i < res.data.length; i++) {
                          if (res.data[i].res == "success") {
                            let datetime = util.formatTime(new Date())
                            dd.httpRequest({
                              url: app.baseUrl + '/DingDingSystem/sendMessage',
                              headers:{
                                "Content-Type":"application/json"
                              },
                              data: JSON.stringify({
                                schoolId: app.globalData.departmentId,
                                template: 1,
                                accessToken: access_token,
                                touser: res.data[i].msg,
                                safetySceneId: safetySceneId,
                                data: {
                                  first: {
                                    value: "【巡检异常】"
                                  },
                                  keyword1: {
                                    value: app.globalData.realname
                                  },
                                  keyword2: {
                                    value: datetime
                                  },
                                  keyword3: {
                                    value: `巡检时在${this.data.address}发现异常，请及时查看!`
                                  }
                                }
                              }),
                              method: 'POST',
                              dataType: 'json'
                            })
                          } else {
                            unbind.push(res.data[i].msg)
                          }
                        }
                        if (unbind.length != 0) {
                          let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                          dd.confirm({
                            title: "提示",
                            content: msg,
                          })
                        }
                      }
                    })
                  },
                  complete: () => {
                    dd.removeStorage({
                      key: 'updateInspect' + this.data.id
                    })
                    dd.removeStorageSync('inspectitemOriginal')
                    setTimeout(function() {
                      let pages = getCurrentPages();
                      let prevPage = pages[pages.length - 2];
                      prevPage.setData({
                        submitRefresh: 1
                      });
                      // 提示框隐藏后 跳转
                      dd.navigateBack({
                        delta: 1
                      })
                    }, 1000)
                  }
                })
              } else {
                dd.showToast({
                  content: '上报失败',
                  type: 'fail'
                })
              }
            },
            fail: res => {
              dd.showToast({
                content: '网络异常！',
                type: 'fail'
              })
            }
          })
        }
      },
      fail: res => {
        dd.showToast({
          content: '网络异常！',
          type: 'fail'
        })
      }
    })
  }
});